<template>
  <div class="max">
    <my-header :backBtn='true'>
      <div slot="right" @click="submit">
        发布
      </div>
    </my-header>
    <div class="weui-cell weui-cell_select weui-cell_select-after">
      <div class="weui-cell__hd">
        <label class="weui-label">班级</label>
      </div>
      <div class="weui-cell__bd">
        <select class="weui-select" v-model="data.clazzId">
          <option :value="item.id" v-for="item in clazzList">{{item.gradeName}}-{{item.name}}</option>
        </select>
      </div>
    </div>
    <div class="cont-nof addDaily">
      <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <textarea maxlength="20" class="weui-textarea" v-model="data.title" placeholder="说点什么"
                      rows="2"></textarea>
            <div class="weui-textarea-counter"><span>{{data.title.length}}</span>/20</div>
          </div>
        </div>
      </div>
      <div class="weui-uploader">
        <div class="weui-uploader__bd">
          <ul class="weui-uploader__files flex my-weui-uploader__files" id="uploaderFiles">
            <li class="pr weui-uploader__file" style="position: relative;" v-for="(item) in previewList"
                v-if="item.type.indexOf('image')!==-1">
              <img @touchstart="previewImage(item.url)" :src="item.url"
                   style="width: 100%;height: 100%;" alt="">
              <i class="pa weui-icon-cancel my-del-icon" @touchstart="del($event,item)"></i>
            </li>
            <li class="pr weui-uploader__file" style="position: relative;width: 100%;height: auto;"
                v-for="(item) in previewList" v-else>
              <video :src="item.url" :controls="true"
                     poster="https://qzy-1258334467.cos.ap-guangzhou.myqcloud.com/video.png"
                     v-if="item.type.indexOf('video')!==-1"
                     style="width: 100%;"></video>
              <i class="pa weui-icon-cancel my-del-icon" @touchstart="del($event,item)"></i>
            </li>
            <!-- 添加图片 -->
            <li class="weui-uploader__file weui-uploader__input-box" v-if="data.type==='image'">
              <input id="uploaderImage" class="weui-uploader__input" type="file" accept="image/*" multiple
                     @change="upload"/>
            </li>
            <!-- 添加视频 -->
            <li class="weui-uploader__file weui-uploader__input-box"
                v-if="data.type==='video'&&previewList.length===0">
              <input id="uploaderVideo" class="weui-uploader__input" type="file" accept="video/*"
                     @change="upload"/>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div v-if="modal.visible">
      <div class="weui-mask"></div>
      <div class="weui-dialog">
        <div class="weui-dialog__hd"><strong class="weui-dialog__title">提示</strong></div>
        <div class="weui-dialog__bd">无可选班级，请联系管理员分配班级</div>
        <div class="weui-dialog__ft">
          <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" @click="sureConfirm">确定</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import wx from "weixin-js-sdk";
  import COS from 'cos-js-sdk-v5';

  export default {
    data() {
      return {
        previewList: [],
        clazzList: [],
        data: {
          type: '',
          clazzId: '',
          title: '',
        },
        cos: null,
        options: {
          bucket: '',
          region: '',
          folder: '',
          domain: '',
        },
        modal: {
          visible: false
        }
      }
    },
    methods: {
      getWxConfig() {
        let url = window.location.href;

        let _this = this;
        _this.$http.fetchWxConfig({url: url}).then(resp => {
          wx.config({
            // debug: true,
            appId: resp.data.appId,
            timestamp: resp.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: resp.data.noncestr, // 必填，生成签名的随机串
            signature: resp.data.sign,// 必填，签名
            jsApiList: ['previewImage'] // 必填，需要使用的JS接口列表
          });
        })
      },
      previewImage(url) {
        wx.previewImage({
          previewImage: url,
          urls: [url]
        })
      },
      submit: function () {
        if (!this.data.clazzId) {
          this.$weui.topTips('请选择班级');
          return;
        }
        if (!this.data.title) {
          this.$weui.topTips('请说点什么');
          return;
        }
        if (this.previewList.length === 0) {
          this.$weui.topTips('请上传素材');
          return;
        }
        this.data.fileList = this.previewList;
        this.$http.createTrendy(this.data).then(resp => {
          this.$router.push('/classDaily')
        })
      },
      upload: function (e) {
        let files = e.target.files;
        if (files.length === 0) {
          return;
        }
        for (let f = 0; f < files.length; f++) {
          let file = files[f];
          let fileName = this.uuid() + file.name.substring(file.name.lastIndexOf('.'));
          this.$toast.show('上传中...', 'loading');
          let that = this;
          this.cos.putObject({
            Bucket: this.options.bucket,
            Region: this.options.region,
            Key: fileName,
            Body: file,
          }, function (err, resp) {
            if (resp.statusCode === 200) {
              let data = {
                fileName: fileName,
                url: that.options.domain + fileName,
                type: file.type,
              };
              that.previewList.push(data);
            }
            that.$toast.hide();
          });
        }
      },
      del(e, item) {
        e.preventDefault();
        this.$http.deleteFile({fileName: item.fileName}).then(resp => {
          let list = this.previewList;
          this.previewList.splice(list.indexOf(item), 1);
        })
      },
      fetchClazzList() {
        this.$http.fetchClazzList().then(resp => {
          let clazzList = resp.data;
          if (clazzList.length === 0) {
            this.modal.visible = true;
          }
          this.clazzList = clazzList;
          if (clazzList.length === 1) {
            this.data.clazzId = clazzList[0].id;
          }
        })
      },
      sureConfirm() {
        this.$router.push('/classDaily')
      },
      uuid() {
        let date = new Date();
        /**
         * @return {string}
         */
        function S4() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (date.getFullYear() + "" + (date.getMonth() + 1) + S4() + S4() + S4() + S4() + S4() + S4());
      },
      getCosCredential() {
        let that = this;
        that.$http.getCosCredential().then(resp => {
          let data = this.options = resp.data;
          this.cos = new COS({
            SecretId: data.secretId,
            SecretKey: data.secretKey,
          });
        });
      }
    },
    mounted() {
      this.fetchClazzList();
      this.getWxConfig();
      this.getCosCredential();
    },
    created() {
      this.data.type = this.$route.query.value;
    }
  }
</script>

<style scoped>
  .addDaily {
    padding: 1rem;
    box-sizing: border-box;
    font-size: 1.4rem;
  }

  .daily-p {
    padding: 0.5rem;
    box-sizing: border-box;
    background: #fff;
  }
</style>
